package com.yds.xutils_facrotypattern.https;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.yds.xutils_facrotypattern.MyApplication;

import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络工具类
 */
@SuppressWarnings("all")
public class XutilsFileHelper {

    private XutilsFileHelper() {
    }

    public static XutilsFileHelper getInstance() {
        return SafeMode.mHttp;
    }

    public static class SafeMode {
        private static final XutilsFileHelper mHttp = new XutilsFileHelper();
    }

    /**
     * 上传文件
     *
     * @param url            网络地址
     * @param filePaths      本地地址
     * @param obj            其它参数
     * @param commonCallBack 请求回调
     */
    public void uploadFile(String url, List<String> filePaths, Object obj, CommonFileCallBack<String> commonCallBack) {
        String json = "";
        List<KeyValue> list = new ArrayList<>();

        //构建RequestParams对象，传入请求的服务器地址URL
        RequestParams params = new RequestParams(ApiConstanse.BASE_URL + url);
        params.setConnectTimeout(300 * 1000);
        params.setReadTimeout(300 * 1000);
        params.setAsJsonContent(true);

        //其它参数
        if (obj != null) {
            Gson gson = new Gson();
            json = gson.toJson(obj);
        }

        //本地文件地址列表
        for (String filePath : filePaths) {
            list.add(new KeyValue("file", new File(filePath)));
        }

        if (!TextUtils.isEmpty(json)) {
            list.add(new KeyValue("parameters", json));
        }

        MultipartBody body = new MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        x.http().post(params, new Callback.ProgressCallback<String>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                commonCallBack.requestProgress((int) (current * 100 / total));
            }

            @Override
            public void onSuccess(String result) {
                Log.i("X-utils","上传文件：onSuccess = " + result);
                commonCallBack.requestSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("X-utils","上传文件：onError = " + ex.toString());
                commonCallBack.requestError(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                //上传完成
                commonCallBack.requestFinished();
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url            下载地址
     * @param commonCallBack 请求回调
     * @param updateAlbum    更新相册
     */
    public void downloadFile(String url, CommonFileCallBack<String> commonCallBack, boolean updateAlbum) {
        url = toUtf8Url(url);
        String saveFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + parseFileName(url);

        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(saveFilePath);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                commonCallBack.requestProgress((int) (current * 100 / total));
            }

            @Override
            public void onSuccess(File file) {
                if (file != null) {
                    Log.i("X-utils","下载文件：onSuccess = " + file.getAbsolutePath());
                    commonCallBack.requestSuccess(file.getAbsolutePath());

                    //是否更新相册
                    if (updateAlbum) {
                        updateAlbum(saveFilePath);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("X-utils","下载文件：onError = " + ex.toString());
                commonCallBack.requestError(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                //下载完成
                commonCallBack.requestFinished();
            }
        });
    }

    /**
     * 将url进行encode，解决部分手机无法下载含有中文url的文件的问题
     *
     * @param url
     * @return
     */
    private String toUtf8Url(String url) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < url.length(); i++) {
            char c = url.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = String.valueOf(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 利用文件url转换出文件名
     *
     * @param url
     * @return
     */
    public String parseFileName(String url) {
        String fileName = null;
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1);
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = String.valueOf(System.currentTimeMillis());
            }
        }
        return fileName;
    }

    /**
     * 更新相册
     *
     * @param saveFilePath 文件下载地址
     */
    private void updateAlbum(String saveFilePath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            File file = new File(saveFilePath);
            String fileName = parseFileName(saveFilePath);
            try {
                MediaStore.Images.Media.insertImage( MyApplication.getApplication().getContentResolver(),
                        file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            MyApplication.getApplication().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
        } else {
            MyApplication.getApplication().sendBroadcast(
                    new Intent(Intent.ACTION_MEDIA_MOUNTED,
                            Uri.parse("file://" + Environment.getExternalStorageDirectory()))
            );
        }
    }

    /**
     * 请求回调
     *
     * @param <T>
     */
    public interface CommonFileCallBack<T> {

        void requestSuccess(T result);

        void requestError(T errorMsg);

        default void requestProgress(int progress) {

        }

        void requestFinished();
    }

}
